package com.sanpu.kxe.business.card.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.sanpu.library.imagechoose.PhotoPicker;
import com.sanpu.kxe.R;
import com.sanpu.kxe.base.BaseEditActivity;
import com.sanpu.kxe.business.card.bean.DefBankOutput;
import com.sanpu.kxe.business.card.contract.OldUpdateDefBankContract;
import com.sanpu.kxe.business.card.presenter.OldUpdateDefBankPresenter;
import com.sanpu.kxe.common.interfaces.CommonConfig;
import com.sanpu.kxe.common.interfaces.UrlConstants;
import com.sanpu.kxe.common.utils.CommonUtils;
import com.sanpu.kxe.common.view.CommonTitleView;
import com.sanpu.kxe.jump.eventbus.ReviewPhotoEvent;
import com.sanpu.kxe.jump.imageloader.JKImageLoader;
import com.sanpu.kxe.module.dialog.HintDialog;
import com.sanpu.kxe.module.widget.EditTextWithDel;
import com.sanpu.kxe.rxservice.RequestMap;
import com.sanpu.kxe.utils.FileUtil;
import com.sanpu.kxe.utils.SoftInputUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Description：修改默认结算卡
 * Created by 薛勇军 on 2019/5/15.
 */

public class OldUpdateDefBankActivity extends BaseEditActivity implements OldUpdateDefBankContract.View {

    @Bind(R.id.commonTitle)
    CommonTitleView commonTitle;

    @Bind(R.id.crdFroIv)
    ImageView crdFroIv;
    @Bind(R.id.crdFro)
    ImageView crdFro;
    @Bind(R.id.crdFroCloud)
    TextView crdFroCloud;

    @Bind(R.id.crdConIv)
    ImageView crdConIv;
    @Bind(R.id.crdCon)
    ImageView crdCon;
    @Bind(R.id.crdConCloud)
    TextView crdConCloud;

    @Bind(R.id.handIv)
    ImageView handIv;
    @Bind(R.id.hand)
    ImageView hand;
    @Bind(R.id.handCloud)
    TextView handCloud;

    @Bind(R.id.etBankNumber)
    EditTextWithDel etBankNumber;
    @Bind(R.id.etPhoneNumber)
    EditTextWithDel etPhoneNumber;

    private OldUpdateDefBankContract.Presenter mPresenter;

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_update_bank_old;
    }

    @Override
    protected void initView() {
        super.initView();
        commonTitle.setTitle("修改结算卡");
        mPresenter = new OldUpdateDefBankPresenter(this);
    }

    @Override
    protected void setListener() {
        super.setListener();
        commonTitle.setLeftOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        etBankNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String current = s.toString().replace(" ", "");
                String format = CommonUtils.bankNumFormatter(current);
                etBankNumber.removeTextChangedListener(this);
                etBankNumber.setText(format);
                etBankNumber.addTextChangedListener(this);
            }

            @Override
            public void afterTextChanged(Editable s) {
                CharSequence text = etBankNumber.getText();
                if (text != null) {
                    Spannable spanText = (Spannable) text;
                    Selection.setSelection(spanText, text.length());
                }
            }
        });
    }

    @OnClick({R.id.commit, R.id.phone_hint, R.id.crdFro, R.id.crdCon, R.id.hand})
    public void commit(View view) {
        switch (view.getId()) {
            case R.id.commit:
                if (!isRespondEvent()) return;
                String bankNo = etBankNumber.getText().toString().replace(" ", "");
                String redTel = etPhoneNumber.getText().toString();
                mPresenter.onCommit(bankNo, redTel);
                break;
            case R.id.phone_hint:
                TextView textView = new TextView(mContext);
                textView.setText("银行预留手机号码是办理该银行卡所填写的手机号码；预留手机号忘记或已停用，请联系银行客服更新处理。");
                new HintDialog(mContext)
                        .title("手机号说明")
                        .content(textView)
                        .show();
                break;
            case R.id.crdFro:
                if (crdFroIv.getTag() != null) {
                    mPresenter.takePhoto((String) crdFroIv.getTag(),
                            CommonConfig.REQUESTCODE_DEFBANK_VIEW_CRDFRO);
                } else {
                    mPresenter.openCertificateHelpActivity(CommonConfig.TYPE_CRDFROPIC);
                }
                break;
            case R.id.crdCon:
                if (crdConIv.getTag() != null) {
                    mPresenter.takePhoto((String) crdConIv.getTag(),
                            CommonConfig.REQUESTCODE_DEFBANK_VIEW_CRDCON);
                } else {
                    mPresenter.openCertificateHelpActivity(CommonConfig.TYPE_CRDCONPIC);
                }
                break;
            case R.id.hand:
                if (handIv.getTag() != null) {
                    mPresenter.takePhoto((String) handIv.getTag(),
                            CommonConfig.REQUESTCODE_DEFBANK_VIEW_IDHAND);
                } else {
                    mPresenter.openCertificateHelpActivity(CommonConfig.TYPE_IDHANDPIC);
                }
                break;
        }
    }

    @Override
    public void showViewData(DefBankOutput output) {
        if (output != null) {
            showLoadingDialog(false, "正在加载图片，请稍后...");
            parseAndDisplayImage(output.getCrdFroPic(), crdFroIv, crdFroCloud, CommonConfig.TYPE_CRDFROPIC);
            parseAndDisplayImage(output.getCrdConPic(), crdConIv, crdConCloud, CommonConfig.TYPE_CRDCONPIC);
            parseAndDisplayImage(output.getIdHandPic(), handIv, handCloud, CommonConfig.TYPE_IDHANDPIC);
            if (!TextUtils.isEmpty(output.getBankNo())) {
                etBankNumber.setText(output.getBankNo());
            }
            if (!TextUtils.isEmpty(output.getRsdTel())) {
                etPhoneNumber.setText(output.getRsdTel());
            }
        }
    }

    /**
     * 照片回显
     */
    private void parseAndDisplayImage(String imageUrl, ImageView imageView, TextView textView, String fileName) {
        if (!TextUtils.isEmpty(imageUrl)) {
            String imgUrl = UrlConstants.getBaseUrl() + imageUrl + RequestMap.sessionIdReqStr();
            imageView.setTag(imgUrl);
            JKImageLoader.getInstance().displayImage(getContext(), imgUrl, imageView);
            textView.setVisibility(View.VISIBLE);
            mPresenter.getImageFileByNet(imgUrl, fileName);
        }
    }

    @Override
    public void onActivityResult(final int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && data != null) {
            ArrayList<String> photos =
                    data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
            switch (requestCode) {
                case CommonConfig.REQUESTCODE_DEFBANK_VIEW_CRDFRO:
                    if (photos == null || photos.size() == 0) {
                        crdFroIv.setTag(null);
                        crdFroIv.setImageDrawable(null);
                        crdFroCloud.setVisibility(View.GONE);
                        mPresenter.removeFile(CommonConfig.TYPE_CRDFROPIC);
                    }
                    break;
                case CommonConfig.REQUESTCODE_DEFBANK_VIEW_CRDCON:
                    if (photos == null || photos.size() == 0) {
                        crdConIv.setTag(null);
                        crdConIv.setImageDrawable(null);
                        crdConCloud.setVisibility(View.GONE);
                        mPresenter.removeFile(CommonConfig.TYPE_CRDCONPIC);
                    }
                    break;
                case CommonConfig.REQUESTCODE_DEFBANK_VIEW_IDHAND:
                    if (photos == null || photos.size() == 0) {
                        handIv.setTag(null);
                        handIv.setImageDrawable(null);
                        handCloud.setVisibility(View.GONE);
                        mPresenter.removeFile(CommonConfig.TYPE_IDHANDPIC);
                    }
                    break;
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(ReviewPhotoEvent event) {
        if (event != null) {
            String filePath = event.getFilePath();
            if (TextUtils.isEmpty(filePath)) {
                return;
            }
            String fileIdName;
            switch (event.getCurrentType()) {
                case CommonConfig.TYPE_CRDFROPIC:
                    fileIdName = CommonConfig.TYPE_CRDFROPIC;
                    JKImageLoader.getInstance().displayImage(mContext, "file://" + filePath, crdFroIv);
                    crdFroIv.setTag(filePath);
                    crdFroCloud.setVisibility(View.VISIBLE);
                    break;
                case CommonConfig.TYPE_CRDCONPIC:
                    fileIdName = CommonConfig.TYPE_CRDCONPIC;
                    JKImageLoader.getInstance().displayImage(mContext, "file://" + filePath, crdConIv);
                    crdConIv.setTag(filePath);
                    crdConCloud.setVisibility(View.VISIBLE);
                    break;
                case CommonConfig.TYPE_IDHANDPIC:
                    fileIdName = CommonConfig.TYPE_IDHANDPIC;
                    JKImageLoader.getInstance().displayImage(mContext, "file://" + filePath, handIv);
                    handIv.setTag(filePath);
                    handCloud.setVisibility(View.VISIBLE);
                    break;
                default:
                    return;
            }
            mPresenter.onCompress(filePath, fileIdName);
        }
    }

    @Override
    protected boolean hasBindEventBus() {
        return true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        SoftInputUtil.hideSoftInput(this);
    }

    @Override
    public void setPresenter(OldUpdateDefBankContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        FileUtil.deleteCache();
        if (mPresenter != null) {
            mPresenter.onDestroyPresenter();
            mPresenter = null;
        }
    }
}
